﻿namespace Blaze.Editor
{
    using System.Collections.Generic;
    using System.Linq;
    using UnityEditor;
    using UnityEngine;

    /// <summary>
    /// AssetBundle关系分析。
    /// </summary>
    public class AssetBundleAnalysisWindow : EditorWindow
    {
        [MenuItem("Blaze/分析/AssetBundle", false, BlazeEditorMenu.Priority.Panels + 2)]
        public static void Open()
        {
            var window = GetWindow<AssetBundleAnalysisWindow>(false, "资源包分析", true);
        }

        private void analysis()
        {
            mCachedAssetBundleNames = AssetDatabase.GetAllAssetBundleNames().OrderBy(assetBundleName => assetBundleName).ToArray();
        }

        private string[] getAssetPathsFromAssetBundle(string assetBundleName)
        {
            string[] ret;
            if (mCachedAssetPathsFromAssetBundle.TryGetValue(assetBundleName, out ret))
                return ret;
            ret = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
            mCachedAssetPathsFromAssetBundle.Add(assetBundleName, ret);
            return ret;
        }

        private void init()
        {
            analysis();
        }

        private void OnGUI()
        {
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("移除所有未使用的资源包名"))
            {
                AssetDatabase.RemoveUnusedAssetBundleNames();
                init();
            }
            if (GUILayout.Button("分析"))
                analysis();

            GUILayout.EndHorizontal();

            mScrollPosition = GUILayout.BeginScrollView(mScrollPosition);
            foreach (var assetBundleName in mCachedAssetBundleNames)
            {
                if (BlazeEditorUtil.DrawHeader(assetBundleName, "analysis_" + assetBundleName, false, false, Color.black))
                {
                    BlazeEditorUtil.BeginContents();
                    var assetPaths = getAssetPathsFromAssetBundle(assetBundleName);
                    foreach (var assetPath in assetPaths)
                    {
                        GUILayout.BeginHorizontal();
                        EditorGUILayout.LabelField(assetPath);
                        if (GUILayout.Button("选中", GUILayout.Width(120)))
                            Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(assetPath);
                        GUILayout.EndHorizontal();
                    }
                    BlazeEditorUtil.EndContents();
                }
            }
            GUILayout.EndScrollView();
        }

        private string[] mCachedAssetBundleNames = new string[0];
        private readonly Dictionary<string, string[]> mCachedAssetPathsFromAssetBundle = new Dictionary<string, string[]>();
        private Vector2 mScrollPosition;
    }
}